package com.zhaojie.savemoney.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.zhaojie.commonutils.StringUtils;
import com.zhaojie.gridview.twoway.TwoWayGridView;
import com.zhaojie.savemoney.R;
import com.zhaojie.savemoney.model.CostRecord;
import com.zhaojie.savemoney.model.CostType;
import com.zhaojie.savemoney.ui.customview.CommonTitleBar;

import org.javia.arity.Symbols;
import org.javia.arity.SyntaxException;

import butterknife.Bind;
import butterknife.ButterKnife;

public class InputActivity extends AppCompatActivity {
    @Bind(R.id.num_tv_add)
    TextView btnAdd;
    @Bind(R.id.num_tv_1)
    TextView btnNum1;
    @Bind(R.id.num_tv_2)
    TextView btnNum2;
    @Bind(R.id.num_tv_3)
    TextView btnNum3;
    @Bind(R.id.num_tv_sub)
    TextView btnSub;
    @Bind(R.id.num_tv_4)
    TextView btnNum4;
    @Bind(R.id.num_tv_5)
    TextView btnNum5;
    @Bind(R.id.num_tv_6)
    TextView btnNum6;
    @Bind(R.id.num_tv_mul)
    TextView btnMul;
    @Bind(R.id.num_tv_7)
    TextView btnNum7;
    @Bind(R.id.num_tv_8)
    TextView btnNum8;
    @Bind(R.id.num_tv_9)
    TextView btnNum9;
    @Bind(R.id.num_tv_div)
    TextView btnDiv;
    @Bind(R.id.num_tv_clear)
    FrameLayout btnClear;
    @Bind(R.id.num_tv_0)
    TextView btnNum0;
    @Bind(R.id.num_tv_point)
    TextView btnPoint;
    @Bind(R.id.num_tv_in)
    RadioButton btnIn;
    @Bind(R.id.num_tv_out)
    RadioButton btnOut;
    @Bind(R.id.type_grid)
    TwoWayGridView gridType;
    @Bind(R.id.add_photo)
    ImageView btnAddPhoto;
    @Bind(R.id.add_remark)
    ImageView btnAddRemark;
    @Bind(R.id.value)
    TextView tvValue;
    @Bind(R.id.value_expr)
    TextView tvValueExpr;
    @Bind(R.id.type)
    TextView type;
    @Bind(R.id.title_layout)
    CommonTitleBar titleBar;

    private CostTypeAdapter costTypeAdapter;
    private StringBuilder valueStr = new StringBuilder();
    private double value;
    private boolean canCalc = true;
    private Symbols mSymbols = new Symbols();
    private CostType costType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input);

        ButterKnife.bind(this);

        initViews();
        initEvent();
    }

    private void initEvent() {
        btnAdd.setOnClickListener(v -> {
            dealNumInput("+", true);
        });
        btnSub.setOnClickListener(v -> {
            dealNumInput("-", true);
        });
        btnMul.setOnClickListener(v -> {
            dealNumInput("*", true);
        });
        btnDiv.setOnClickListener(v -> {
            dealNumInput("/", true);
        });
        btnNum0.setOnClickListener(v -> {
            dealNumInput("0", false);
        });
        btnNum1.setOnClickListener(v -> {
            dealNumInput("1", false);
        });
        btnNum2.setOnClickListener(v -> {
            dealNumInput("2", false);
        });
        btnNum3.setOnClickListener(v -> {
            dealNumInput("3", false);
        });
        btnNum4.setOnClickListener(v -> {
            dealNumInput("4", false);
        });
        btnNum5.setOnClickListener(v -> {
            dealNumInput("5", false);
        });
        btnNum6.setOnClickListener(v -> {
            dealNumInput("6", false);
        });
        btnNum7.setOnClickListener(v -> {
            dealNumInput("7", false);
        });
        btnNum8.setOnClickListener(v -> {
            dealNumInput("8", false);
        });
        btnNum9.setOnClickListener(v -> {
            dealNumInput("9", false);
        });
        btnPoint.setOnClickListener(v -> {
            dealNumInput(".", true);
        });
        btnClear.setOnClickListener(v -> {
            dealNumInput("", false);
        });

        btnOut.setOnClickListener(v -> {
            costTypeAdapter.setTypeKind(CostType.OUTPUT_KIND);
        });
        btnIn.setOnClickListener(v -> {
            costTypeAdapter.setTypeKind(CostType.INPUT_KIND);
        });

        gridType.setOnItemClickListener((parent, view, position, id) -> {
            costType = ((CostTypeAdapter.ViewHolder) view.getTag()).costType;
            type.setText(costType.name);
        });

        titleBar.setRightBtnOnclickListener(v -> {
            if (costType == null) {
                Toast.makeText(InputActivity.this, "亲， 先选择这笔帐是干啥的！", Toast.LENGTH_LONG).show();
                return;
            }

            if (value == 0) {
                Toast.makeText(InputActivity.this, "记账怎么没有写多少钱呢？", Toast.LENGTH_LONG).show();
                return;
            }
            new CostRecord(costType, 0, value, "", "", "").save();
            finish();
        });

        titleBar.setLeftBtnOnclickListener(v -> {
            finish();
        });
    }

    private void dealNumInput(String input, boolean isOperator) {
        if (StringUtils.isEmpty(input) && valueStr.length() > 0) {
            valueStr.deleteCharAt(valueStr.length() - 1);
            if (valueStr.length() == 0) {
                tvValue.setText("");
                tvValueExpr.setText("");
                return;
            }

            if (isOperator(valueStr.charAt(valueStr.length() - 1))) {
                canCalc = false;
            } else {
                canCalc = true;
            }
        } else if (valueStr.length() == 0) {
            if (isOperator) {
                return;
            } else {
                valueStr.append(input);
                canCalc = true;
            }
        } else {
            if (isOperator && canCalc) {
                valueStr.append(input);
                canCalc = false;
            } else if (isOperator && !canCalc) {
                valueStr.deleteCharAt(valueStr.length() - 1);
                valueStr.append(input);
                canCalc = false;
            } else if (!isOperator && canCalc) {
                valueStr.append(input);
                canCalc = true;
            } else if (!isOperator && !canCalc) {
                valueStr.append(input);
                canCalc = true;
            }
        }

        tvValueExpr.setText(valueStr.toString());
        int size = valueStr.length();
        String expr = valueStr.toString();
        while (size > 0 && isOperator(expr.charAt(size - 1))) {
            expr = expr.substring(0, size - 1);
            --size;
        }
        try {
            value = mSymbols.eval(expr);
            tvValue.setText(" " + value);
        } catch (SyntaxException e) {
            e.printStackTrace();
        }
    }

    private void initViews() {
        costTypeAdapter = new CostTypeAdapter(this, CostType.OUTPUT_KIND);
        gridType.setAdapter(costTypeAdapter);
    }

    static boolean isOperator(String text) {
        return text.length() == 1 && isOperator(text.charAt(0));
    }

    static boolean isOperator(char c) {
        return "+-*//".indexOf(c) != -1;
    }
}
